<template>
  <div class="user-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-text">
          <h2 class="page-title">
            <el-icon class="title-icon"><User /></el-icon>
            用户管理
          </h2>
          <p class="page-description">管理系统用户账户、角色和权限</p>
        </div>
        <div class="header-stats">
          <div class="stat-card">
            <div class="stat-number">{{ users.length }}</div>
            <div class="stat-label">总用户数</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar-container">
      <div class="toolbar">
        <div class="toolbar-left">
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户..."
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
        <div class="toolbar-right">
          <el-button 
            class="refresh-btn" 
            @click="loadUsers"
            :loading="loading"
          >
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button 
            type="primary" 
            @click="showCreateDialog = true"
            class="create-btn"
          >
            <el-icon><Plus /></el-icon>
            新增用户
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 用户列表 -->
    <div class="user-list-container">
      <div class="user-table-wrapper">
        <el-table 
          :data="filteredUsers" 
          v-loading="loading" 
          class="user-table"
          height="100%"
        >
          <el-table-column prop="username" label="用户名" width="150">
            <template #default="{ row }">
              <div class="user-info">
                <div class="user-avatar">
                  <el-icon><User /></el-icon>
                </div>
                <div class="user-details">
                  <div class="username">{{ row.username }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="full_name" label="姓名" width="150">
            <template #default="{ row }">
              <span class="full-name">{{ row.full_name }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="email" label="邮箱" width="220">
            <template #default="{ row }">
              <div class="email-info">
                <el-icon class="email-icon"><Message /></el-icon>
                <span>{{ row.email }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="role" label="角色" width="120">
            <template #default="{ row }">
              <el-tag 
                :type="getRoleTagType(row.role)"
                class="role-tag"
              >
                <el-icon class="tag-icon">
                  <component :is="getRoleIcon(row.role)" />
                </el-icon>
                {{ getRoleText(row.role) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="部门" width="150">
            <template #default="{ row }">
              <div class="department-info">
                <el-icon class="dept-icon"><OfficeBuilding /></el-icon>
                <span>{{ getDepartmentName(row.department_id) }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="160" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="editUser(row)"
                  class="action-btn"
                >
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="deleteUser(row)"
                  :disabled="row.id === authStore.user?.id"
                  class="action-btn"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <!-- 创建/编辑用户对话框 -->
    <el-dialog 
      v-model="showCreateDialog" 
      :title="isEdit ? '编辑用户' : '新增用户'" 
      width="500px"
    >
      <el-form 
        :model="userForm" 
        :rules="userRules" 
        ref="userFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="userForm.username" 
            :disabled="isEdit"
            placeholder="请输入用户名" 
          />
        </el-form-item>
        
        <el-form-item label="姓名" prop="full_name">
          <el-input v-model="userForm.full_name" placeholder="请输入姓名" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input 
            v-model="userForm.password" 
            type="password" 
            placeholder="请输入密码" 
          />
        </el-form-item>
        
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
            <el-option label="部门经理" value="manager" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="部门" prop="department_id">
          <el-select v-model="userForm.department_id" placeholder="请选择部门" clearable>
            <el-option 
              v-for="dept in departments" 
              :key="dept.id"
              :label="dept.name" 
              :value="dept.id" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="saveUser">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  User, 
  Search, 
  Refresh, 
  Edit, 
  Delete, 
  Message, 
  OfficeBuilding,
  UserFilled,
  Avatar,
  Star
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import api from '@/utils/api'

const authStore = useAuthStore()

// 响应式数据
const users = ref([])
const departments = ref([])
const loading = ref(false)
const showCreateDialog = ref(false)
const isEdit = ref(false)
const currentUserId = ref(null)
const searchKeyword = ref('')

// 计算属性
const filteredUsers = computed(() => {
  if (!searchKeyword.value) {
    return users.value
  }
  
  const keyword = searchKeyword.value.toLowerCase()
  return users.value.filter(user => 
    user.username.toLowerCase().includes(keyword) ||
    user.full_name.toLowerCase().includes(keyword) ||
    user.email.toLowerCase().includes(keyword)
  )
})

// 表单数据
const userForm = reactive({
  username: '',
  full_name: '',
  email: '',
  password: '',
  role: 'user',
  department_id: null
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  full_name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 引用
const userFormRef = ref()

// 方法
const loadUsers = async () => {
  loading.value = true
  try {
    const response = await api.get('/users/')
    users.value = response.data
  } catch (error) {
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

const loadDepartments = async () => {
  try {
    const response = await api.get('/departments/')
    departments.value = response.data
  } catch (error) {
    ElMessage.error('加载部门列表失败')
  }
}

const editUser = (user) => {
  isEdit.value = true
  currentUserId.value = user.id
  Object.assign(userForm, {
    username: user.username,
    full_name: user.full_name,
    email: user.email,
    password: '',
    role: user.role,
    department_id: user.department_id
  })
  showCreateDialog.value = true
}

const saveUser = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          // 编辑用户
          const updateData = {
            full_name: userForm.full_name,
            email: userForm.email,
            role: userForm.role,
            department_id: userForm.department_id
          }
          await api.put(`/users/${currentUserId.value}`, updateData)
          ElMessage.success('用户更新成功')
        } else {
          // 创建用户
          await api.post('/users/', userForm)
          ElMessage.success('用户创建成功')
        }
        
        showCreateDialog.value = false
        resetForm()
        loadUsers()
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新用户失败' : '创建用户失败')
      }
    }
  })
}

const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.full_name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.delete(`/users/${user.id}`)
    ElMessage.success('用户删除成功')
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除用户失败')
    }
  }
}

const resetForm = () => {
  Object.assign(userForm, {
    username: '',
    full_name: '',
    email: '',
    password: '',
    role: 'user',
    department_id: null
  })
  isEdit.value = false
  currentUserId.value = null
}

const getRoleText = (role) => {
  const roleMap = {
    admin: '管理员',
    user: '普通用户',
    manager: '部门经理'
  }
  return roleMap[role] || role
}

const getRoleTagType = (role) => {
  const typeMap = {
    admin: 'danger',
    manager: 'warning',
    user: 'info'
  }
  return typeMap[role] || 'info'
}

const getDepartmentName = (departmentId) => {
  if (!departmentId) return '-'
  const dept = departments.value.find(d => d.id === departmentId)
  return dept ? dept.name : '-'
}

const getRoleIcon = (role) => {
  const iconMap = {
    admin: Avatar,
    manager: Star,
    user: UserFilled
  }
  return iconMap[role] || UserFilled
}

const handleSearch = () => {
  // 搜索功能由计算属性自动处理
}

// 生命周期
onMounted(() => {
  loadUsers()
  loadDepartments()
})
</script>

<style scoped>
.user-management {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--bg-primary);
}

/* 页面头部样式 */
.page-header {
  background: linear-gradient(135deg, var(--color-primary), var(--color-success));
  color: white;
  padding: 32px 24px;
  position: relative;
  overflow: hidden;
}

.page-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="1"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
  opacity: 0.3;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  z-index: 1;
}

.header-text {
  flex: 1;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-icon {
  font-size: 32px;
  opacity: 0.9;
}

.page-description {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
  font-weight: 400;
}

.header-stats {
  display: flex;
  gap: 20px;
}

.stat-card {
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(10px);
  border-radius: var(--border-radius-lg);
  padding: 20px;
  text-align: center;
  border: 1px solid rgba(255, 255, 255, 0.2);
  min-width: 120px;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 4px;
  color: white;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
  font-weight: 500;
}

/* 工具栏样式 */
.toolbar-container {
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-color);
  padding: 16px 24px;
  backdrop-filter: blur(10px);
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 100%;
}

.toolbar-left {
  display: flex;
  align-items: center;
}

.search-box {
  width: 300px;
}

.search-box :deep(.el-input__wrapper) {
  border-radius: var(--border-radius-md);
  transition: all var(--transition-base);
}

.search-box :deep(.el-input__wrapper:hover) {
  border-color: var(--color-primary);
}

.toolbar-right {
  display: flex;
  gap: 12px;
}

.refresh-btn,
.create-btn {
  height: 36px;
  border-radius: var(--border-radius-md);
  transition: all var(--transition-base);
}

.refresh-btn {
  border: 1px solid var(--border-color);
  background: var(--bg-secondary);
}

.refresh-btn:hover {
  background: var(--bg-tertiary);
  border-color: var(--color-primary);
  transform: translateY(-1px);
}

.create-btn:hover {
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
}

/* 用户列表样式 */
.user-list-container {
  flex: 1;
  padding: 24px;
  overflow: hidden;
}

.user-table-wrapper {
  height: 100%;
  background: var(--bg-secondary);
  border-radius: var(--border-radius-lg);
  overflow: hidden;
  box-shadow: var(--shadow-sm);
}

.user-table {
  height: 100%;
}

.user-table :deep(.el-table__header) {
  background: var(--bg-tertiary);
}

.user-table :deep(.el-table__row) {
  transition: all var(--transition-base);
  cursor: pointer;
}

.user-table :deep(.el-table__row:hover) {
  background: var(--bg-tertiary);
  transform: scale(1.001);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--color-primary), var(--color-info));
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
}

.user-details {
  flex: 1;
}

.username {
  font-weight: 500;
  color: var(--text-primary);
}

.full-name {
  font-weight: 500;
  color: var(--text-primary);
}

.email-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--text-secondary);
}

.email-icon {
  font-size: 16px;
  color: var(--color-primary);
}

.role-tag {
  display: flex;
  align-items: center;
  gap: 6px;
  border-radius: var(--border-radius-md);
  font-weight: 500;
}

.tag-icon {
  font-size: 14px;
}

.department-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--text-secondary);
}

.dept-icon {
  font-size: 16px;
  color: var(--color-warning);
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-btn {
  border-radius: var(--border-radius-sm);
  transition: all var(--transition-base);
}

.action-btn:hover {
  transform: scale(1.05);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .toolbar {
    flex-direction: column;
    gap: 16px;
  }
  
  .toolbar-left,
  .toolbar-right {
    width: 100%;
    justify-content: center;
  }
  
  .search-box {
    width: 100%;
  }
  
  .user-list-container {
    padding: 16px;
  }
  
  .toolbar-container {
    padding: 12px 16px;
  }
  
  .page-header {
    padding: 24px 16px;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 24px;
  }
  
  .stat-card {
    min-width: 100px;
    padding: 16px;
  }
  
  .stat-number {
    font-size: 24px;
  }
  
  .toolbar-right {
    flex-direction: column;
    width: 100%;
  }
  
  .user-table :deep(.el-table__cell) {
    padding: 8px 4px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
}

/* 动画效果 */
.user-table :deep(.el-table__row) {
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.stat-card {
  animation: slideUp 0.4s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>